import { Breadcrumb, Button, Divider, Flex, Form, Input, Radio, Select, Space, Spin, Table } from "antd";
import styled from "styled-components";
import { Link } from "react-router-dom";
import { MinusCircleOutlined } from '@ant-design/icons';
import { useParams } from "@/router/hooks";
import { useEffect, useState } from "react";
import { useDictionary } from "@/hooks";
import DisplayLabel from "@/components/displayLabel";
import { dataSubjectDetail, commonServiceDoService } from '@/api/sharing/dataSubject'
import CodeEditor from "@/components/codemirror/CodeEditor";


const DataCatalogTryout = () => {
  useDictionary(['param_type'])
  const [form] = Form.useForm();
  const { id: detailId } = useParams();
  const [fullData, setFullData] = useState({})
  const [countTime, setCountTime] = useState(0)
  const [response, setResponse] = useState('')
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    dataSubjectDetail({ id: detailId }).then((res) => {
      setFullData(res?.result || {})
      const data = res?.result || {}
      form.setFieldsValue({
        accessUrl: data.accessUrl,
        accessType: data.accessType,
        paramList: data.paramList || [],
      })
    })
  }, [])


  const columns = [
    {
      title: '参数名',
      dataIndex: 'paramName',
    },
    {
      title: '参数类型',
      dataIndex: 'paramType',
      render: (text) => {
        return <DisplayLabel value={text} type="param_type"></DisplayLabel>
      }
    },
    {
      title: '参数说明',
      dataIndex: 'paramRemark',
    },
    {
      title: '参数值',
      dataIndex: 'paramValue',
      width: '28%',
      render: (text, record, index) => {
        return <Form.Item
          name={['paramList', index, 'paramValue']}
          rules={[
            // ({ getFieldValue }) => ({
            //   validator(_, value) {
            //     if (value && getFieldValue(['paramList', index, 'paramType']) === 'boolean') {
            //       if(value !== 'true' && value !== 'false' {
            //         return Promise.reject('请填写布尔类型参数');
            //       }
            //     }

            //     return Promise.resolve();
            //   },
            // })
          ]}>
          <Input
            placeholder="参数值"
          />
        </Form.Item>
      }
    },
    // {
    //   title: '操作',
    //   key: 'action',
    //   render: (_, record) => (
    //     <>
    //       <a onClick={() => tableDelete(record)}>删除</a>
    //     </>
    //   ),
    // }
  ]


  const tableDelete = (record) => {
    let ids = record ? [record.id] : selectedRowKeys
    let data = form.getFieldValue('paramList') || []
    form.setFieldValue('paramList', data.filter(item => !ids.includes(item.id)))
  }


  const handleSend = () => {
    setLoading(true)
    const t = new Date().getTime()
    let paramList = form.getFieldValue('paramList') || []
    const params = {
      "resourceSign": fullData.themeSign,
      "requestParams": paramList
    }
    commonServiceDoService(params).then(res => {
      if (typeof res.result === 'string') {
        res.result = JSON.parse(res.result)
      }
      setResponse(JSON.stringify(res, null, '\t'))
    }).finally(() => {
      setCountTime(new Date().getTime() - t)
      setLoading(false)
    })
  }

  return (<StyleWrap>
    <div className="page-breadcrumb">
      <Breadcrumb
        items={[
          {
            title: <Link to="/integration/sharing/dataCatalog">数据目录</Link>,
          },
          {
            title: 'API测试',
          }
        ]}
      />
    </div>
    <div className="header-bar">
      <span className="title">基本参数配置</span>
      <span className="title">服务测试</span>
      {
        !!countTime && <span className="header-bar-time">请求耗时：<span>{countTime} ms</span></span>
      }
    </div>
    <div className="content-wrapper">
      <div className="left-box">
        <Form form={form} labelAlign="right" labelCol={{ span: 5 }}>
          <Form.Item name="accessUrl" label="服务地址">
            <Input placeholder='服务地址' readOnly />
          </Form.Item>
          <Form.Item name="accessType" label="请求方法">
            <Input placeholder='请求方法' readOnly />
          </Form.Item>
          {/* <Form.Item name="ljcs" label="路径参数">
            <FormParamsLit />
          </Form.Item>
          <Form.Item name="qqt" label="请求头">
            <FormRequestBody />
          </Form.Item> */}
          <Form.Item name={'paramList'} valuePropName="dataSource" label="查询参数">
            <Table
              rowKey="id"
              size="small"
              columns={columns}
              pagination={false}
              bordered
            />
          </Form.Item>
        </Form>
        <Flex justify={'center'}>
          <Space size="large">
            {/* <Link to={`/integration/catalog/serviceCatalog/${detailId}/edit`}><Button>前往编辑</Button></Link> */}
            <Button onClick={handleSend} type="primary" loading={loading}>发送请求</Button>
          </Space>
        </Flex>
      </div>
      <Divider type="vertical" />
      <div className="right-box">
        {/* <div className="preview-title">请求</div>
        <pre className="preview-content">
          GET /api/echo HTTP/1.1<br />
          Host: eb65c2f1607641c885d2458a00f8d8fb.apig.cn-east-3.huaweicloudapis.com<br />
          User-Agent: APIGatewayDebugClient/1.0<br />
          X-Apig-Mode: debug
        </pre> */}

        <div className="preview-title">响应</div>
        <div className="preview-content">
          <Spin spinning={loading}>
            <CodeEditor value={response} onChange={(val) => {
              setFormData({ nodeResult: val })
            }} height={'300px'} lang="json" readOnly />
          </Spin>
        </div>
      </div>
    </div>
  </StyleWrap>);
}

const FormParamsLit = ({ value = [], onChange }) => {
  const onInput = (index, key, val) => {
    onChange(value.map((item, i) => i === index ? { ...item, [key]: val } : item))
  }

  return <StyleFormParamsLit>
    <table>
      <thead>
        <tr>
          <th>参数名</th>
          <th>参数类型</th>
          <th>参数说明</th>
          <th>参数值</th>
          <th className="action">操作</th>
        </tr>
      </thead>
      <tbody>
        {value.map((item, index) => (
          <tr key={index}>
            <td>
              {item.paramName}
              {/* <input placeholder="请输入参数名" value={item.key} onChange={(e) => onInput(index, 'key', e.target.value)} /> */}
            </td>
            <td>
              <DisplayLabel value={item.paramType} type="param_type"></DisplayLabel>
            </td>
            <td>
              {item.paramRemark}
            </td>
            <td>
              <input placeholder="请输入参数值" value={item.paramValue} onChange={(e) => onInput(index, 'paramValue', e.target.value)} />
            </td>
            <td className="action">
              <Button shape="circle" type="text" danger onClick={() => onChange(value.filter((_, i) => i !== index))}>
                <MinusCircleOutlined />
              </Button>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
    <Button size="small" type="primary" onClick={() => onChange([...value, { key: '', value: '' }])}>添加参数</Button>
  </StyleFormParamsLit>
}

const FormRequestBody = ({ value, onChange }) => {
  return <StyleFormRequestBody>
    <div className="radio-group">
      <Radio.Group
        value={value}
        onChange={onChange}
        options={[{ label: 'form-data', value: '1' }, { label: 'x-www-form-urlencoded', value: '2' }, { label: 'raw', value: '3' }]}
      />
    </div>

    <table>
      <thead>
        <tr>
          <th>KEY</th>
          <th>VALUE</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>
          </td>
          <td>
          </td>
        </tr>
      </tbody>
    </table>
  </StyleFormRequestBody>;
}

const StyleWrap = styled.div`
  padding: 16px;
  .header-bar{
    display: flex;
    align-items: center;
    border: 1px solid #326394;
     border-radius: 2px;
     line-height: 50px;
     font-size: 16px;
     font-weight: bold;
     position: relative;
    .title{
      width: 50%;
      flex-shrink: 0;
    }
    .title:first-child{
      padding-left: 16px;
    }
  }

  .header-bar-time{
    position: absolute;
    right: 16px;
  }

  .content-wrapper{
    display: flex;
    margin-top: 30px;
    & > .ant-divider-vertical{
      height: unset;
    }
  }

  .left-box{
    flex: 1;
  }
  .right-box{
    flex: 1;
    width: 0;
  }

  .preview-content{
    border: 1px solid rgba(116, 186, 251, 0.43);
    /* background-color: rgba(255, 255, 255, 0.04); */
    /* height: 290px; */
    overflow: auto;
    border-radius: 2px;
    margin-top: 10px;
    margin-bottom: 30px;
    /* padding: 10px; */
    white-space: pre-wrap;
  }
  .preview-title{
    font-weight: bold;
  }

  .ant-table-wrapper .ant-table .ant-form-item {
    margin-bottom: 0 ;
  }
`

const StyleFormParamsLit = styled.div`
  table{
    width: 100%;
    border-collapse:collapse;
    border-style: solid;
    border-width: 1px;
    margin-bottom: 10px;
  }
  td,th{
    border: 1px solid #326394;
    height: 32px;
    padding: 0;
  }
  tbody{
    
  }
  input{
    border: none;
    background-color: unset;
    outline: none;
    width: 100%;
    height: 100%;
    padding: 0 10px;
  }
  .action{
    width: 50px;
    text-align: center;
  }
`

const StyleFormRequestBody = styled.div`
  table{
    width: 100%;
    border-collapse:collapse;
    border-style: solid;
    border-width: 1px;
    margin-top: 10px;
  }
  td,th{
    border: 1px solid #326394;
    height: 32px;
    padding: 0;
  }
  tbody{}
  .radio-group{
    line-height: 32px;
  }
`
export default DataCatalogTryout;